$(() => {
  menuToggle($("#warehouseMenu .select").prop("title"));

  $("#warehouseMenu").on("click", "li", function(e) {
    if ($(this).hasClass("select")) return;

    $(this)
      .addClass("select")
      .siblings("li")
      .removeClass("select");

    $("#warehouseTitle").text($(this).text());
    menuToggle($(this).prop("title"));
  });

  // 点击关闭进仓明细
  $(".closealter-en").on("click", function() {
    $(".enterStorageDetail")
      .removeClass("fide-out show")
      .addClass("fade-in hide");
  });
});

// 关闭数量弹框
$("#alter-close").on("click", function() {
  $(".insert-returnNumber")
    .removeClass("fide-out show")
    .addClass("fade-in hide");
});

// 点击弹出采购退货明细
$(".retrunHouseDetailBotton").on("click", function() {
  $(".retrunHouseDetail")
    .removeClass("fide-out hide")
    .addClass("fade-in show");
});

// 点击关闭采购退货明细
$(".closealter-re").on("click", function() {
  $(".retrunHouseDetail")
    .removeClass("fide-out show")
    .addClass("fade-in hide");
});

// 变色
// $("#warehouseContainer").on("mouseover", "table tr", function(e) {
//   oldColor = $(this).css("background-color");
//   $(this).css("background", "#333");
// });

//菜单切换
function menuToggle(title) {
  if (title === "saleReturn") {
    new Return({ type: 1 });
    return;
  } else if (title === "procurementReturn") {
    new Return({ type: 0 });
    return;
  }

  const type = title === "enterWarehouseByProcurement" ? 0 : 1;
  new EnterWarehouse({ type });
}

//表格
class Table {
  constructor({
    type,
    keyToDetail,
    url,
    element,
    rootElement,
    paramObj,
    noParam,
    name
  }) {
    this.pageTotal = 0;
    this.pageNum = 1;
    this.rootElement = rootElement || "#warehouseContainer";
    this.element = element || "#warehouseTable";
    this.baseUrl = "http://www.fjemiot.cn/erp/";
    this.url = url;
    this.type = type;
    this.keyToDetail = keyToDetail;
    this.valueToDetail = null;
    this.rowObj = null;
    this.paramObj = paramObj || {
      type,
      pageSize: 10
    };
    this.noParam = noParam;
    this.name = name;

    this.eventInit();
    this.tableEventInit();
  }

  /**
   * 表格初始化
   * @param {string} btn 上一页/下一页
   */
  tableInit(btn) {
    let endUrl = "";
    // console.log(this.noParam);
    if (!this.noParam) {
      //params的参数
      let params = "?";
      const paramObj = { ...this.paramObj, pageNum: this.pageNum };
      for (let key in paramObj) {
        params += `${key}=${paramObj[key]}&`;
      }
      // console.log(params);
      endUrl = `${this.baseUrl}${this.url}${params.substring(
        0,
        params.length - 1
      )}`;
      // console.log(params.substring(0, params.length - 1));
    } else {
      //url参数
      endUrl = this.url(this.baseUrl, this.pageNum);
    }

    btn & $(btn).attr("disabled", true);
    this.renderTable();
    $.ajax({
      url: endUrl
    })
      .then(res => {
        const body = this.getTableBody(res);
        this.renderTable(body);
        this.pageTotal = res.total;
      })
      .always(() => {
        btn & $(btn).attr("disabled", false);
      });
  }
  // 获取表格
  getTableBody(res) {
    if (!res) {
      $(this.element).html();
      return;
    }
    const value = res.value;
    const body = value.map(item => {
      const date = this.handleColumn(item.date, "dateTime"); //转换为年月日时分秒
      const state = this.handleColumn(item.state, this.getEnterWarehouseState); //转换为中文状态
      const type = this.handleColumn(item.type, this.getEnterWarehouseType); //转换进仓类型
      return {
        ...item,
        date,
        type,
        state
      };
    });
    return body;
  }
  renderTable(body = []) {
    const table = document.createElement("table");
    $(table).html("<table><thead><tr></tr></thead><tbody></tbody></table>");

    const headObj = body.length ? body[0] : this.tableHead; //没数据只渲染表头
    // console.log(headObj.product);
    for (const t in headObj.product ? headObj.product : headObj) {
      if (t == "returnDetails") continue;
      const text = this.tableHead[t];
      const th = `<th>${text}</th>`;
      $(table)
        .find("thead>tr")
        .append(th);
    }

    if (typeof body !== "object" || body.length === 0) {
      $(this.element).html(table);
      return;
    }

    for (let obj of body) {
      let newTr = document.createElement("tr");
      newTr.setAttribute("keyToDetail", obj[this.keyToDetail]);
      newTr.setAttribute("obj", JSON.stringify(obj));
      const secondObj = obj.product ? obj.product : obj;
      // console.log(obj);
      for (let index in secondObj) {
        let newTd = document.createElement("td");
        newTd.innerHTML = secondObj[index];
        newTr.append(newTd);
      }
      $(table)
        .children("tbody")
        .append(newTr);
    }

    // return $table;
    $(this.element).html(table);
  }

  //事件初始化
  eventInit() {
    const self = this;
    // console.log(self);
    $(this.rootElement)
      .off("click")
      .on("click", "button", function(e) {
        if ($(this).hasClass("change-page")) {
          //分页相关
          const next = $(this).hasClass("chl") ? false : true; //是否是下一页
          if (next) {
            //下一页
            if (self.pageNum >= self.pageTotal) {
              tip.alert("已经是最后一页了", "进仓", "warn", 500);
              return;
            }
            self.pageNum++;
          } else {
            //上一页
            if (self.pageNum <= 1) {
              tip.alert("已经是第一页了", "进仓", "warn", 500);
              return;
            }
            self.pageNum--;
          }
          self.tableInit($(this));
        } else if ($(this).is("#delProduct")) {
          //删除
          $.ajax({
            url: `${self.baseUrl}${self.url}/${self.valueToDetail}`,
            method: "delete"
          }).then(res => {
            tip.alert("删除成功", "提示", "success", 1000);
            self.tableInit();
          });
        } else if ($(this).is("#addProduct")) {
          if (!self.valueToDetail) {
            tip.alert("请先选要操作的行", "提示", "warn", 500);
            return;
          }
          // 传送到getDetaiL里
          if (self.name === "enterWarehouse") {
            getEnterWarehousDetail(self.valueToDetail, self.rowObj);

            // 点击弹出进仓明细
            $(".enterStorageDetail")
              .removeClass("fide-out hide")
              .addClass("fade-in show");
          } else if (self.name === "return") {
            //TODO:这里放退货的详情
            // console.log("hey");
            getBuyReturnDetail(self.valueToDetail, self.rowObj);
            // 点击弹框
            $(".retrunHouseDetail")
              .removeClass("fide-out hide")
              .addClass("fade-in show");
          }
        } else if ($(this).is("#updProduct")) {
          //TODO:修改
          if (!self.valueToDetail) {
            tip.alert("请先选要操作的行", "提示", "warn", 500);
            return;
          }
          if (self.name === "enterWarehouse") {
            getEnterWarehousDetail(self.valueToDetail, self.rowObj);
            console.log(self.name);
            // 点击弹出进仓明细
            $(".enterStorageDetail")
              .removeClass("fide-out hide")
              .addClass("fade-in show");
          } else if (self.name === "return") {
            console.log("hey");
            getBuyReturnDetail(self.valueToDetail, self.rowObj);

            // 点击弹框
            $(".retrunHouseDetail")
              .removeClass("fide-out hide")
              .addClass("fade-in show");
          }
          console.log(self.valueToDetail);
        }
      });
  }

  //表格事件初始化
  tableEventInit() {
    const self = this;
    // console.log(self);
    $(this.element)
      .off("click")
      .on("click", "tbody>tr", function() {
        // 点击每行获取到的单号
        const valueToDetail = $(this).attr("keyToDetail");
        // 获取每行获得的json对象
        const obj = $(this).attr("obj");
        $(this)
          .addClass("select")
          .siblings()
          .removeClass("select");
        self.valueToDetail = valueToDetail;
        self.rowObj = JSON.parse(obj); //获取到的数组放进去
      });

    $(this.element)
      .off("mouseover")
      .on("mouseover", "tbody>tr", function() {
        $(this)
          .addClass("select1")
          .siblings()
          .removeClass("select1");
      });
    $(this.element)
      .off("mouseout")
      .on("mouseout", "tbody>tr", function() {
        $(this).removeClass("select1");
      });
  }

  /**
   * 处理列
   * @param {String} value
   * @param {String|Function} fn
   */
  // 处理时间
  handleColumn = (value, fn) => {
    if (fn === "dateTime") {
      return timeTransform(value);
    }
    return fn(value);
  };

  //获取进仓类型
  getEnterWarehouseType = num => {
    return this.types[num];
  };

  //获取进仓状态
  getEnterWarehouseState = num => {
    return this.states[num];
  };

  //进仓审核状态
  states = {
    "-1": "未通过",
    0: "未审核",
    1: "未执行",
    2: "已执行"
  };

  //进仓类型
  types = { 0: "采购", 1: "销售" };
}

//进仓表格
class EnterWarehouse extends Table {
  constructor({ type }) {
    super({
      type,
      keyToDetail: "entryStorageNo",
      url: "enterStorage",
      name: "enterWarehouse"
    });
    this.element = "#warehouseTable";
    this.type = type;
    this.url = "enterStorage";
    this.init();
  }

  init() {
    $("#addProduct").html("退货");
    $("#updProduct").html("修改");
    super.tableInit();
  }

  //进仓-表头
  tableHead = {
    date: "时间",
    orderNo: "订单号",
    carNo: "到货车号",
    freight: "运费",
    supplierNo: "供应商编号",
    state: "状态",
    entryStorageNo: "进仓号",
    employeeNo: "业务员号",
    type: " 类型"
  };
}
//退货表格
class Return extends Table {
  constructor({ type }) {
    super({
      type,
      keyToDetail: "returnNo",
      url: "returnMaster",
      name: "return"
    });
    this.element = "#warehouseTable";
    this.url = "returnMaster";
    this.type = type;
    this.init();
  }

  init() {
    $("#addProduct").html("查看退货单");
    $("#updProduct").html("修改退货单");
    super.tableInit();
  }

  //退货-表头
  tableHead = {
    returnNo: "退货单号",
    signNo: this.type ? "销售进仓单号" : "采购出仓单号",
    type: "类型",
    state: "状态",
    employeeNo: "员工编号",
    date: "时间"
  };
}

// 采购进仓明细表
class EnterWarehouseDetail extends Table {
  constructor({ url, noParam, mainRowObj }) {
    super({
      url,
      noParam,
      rootElement: "#enterStorageDetail",
      element: "#entryHouseProductTable"
    });
    this.element = "#entryHouseProductTable";
    this.url = url;
    this.mainRowObj = mainRowObj;
    this.init();
  }
  formInit() {
    const {
      date,
      orderNo,
      // carNo,
      // freight,
      employeeNo,
      supplierNo
      // state,
      // entryStorageNo,
      // type
    } = this.mainRowObj;
    console.log(this.mainRowObj);
    $("#enterStorageDetail #enter-employeeNo").val(employeeNo);
    $("#enterStorageDetail #enter-orderNo").val(orderNo);
    $("#enterStorageDetail #enter-date").val(timeTransform(date));
    $("#enterStorageDetail #enter-supplierNo").val(supplierNo);
  }

  init() {
    super.tableInit();
    this.btnEventInit();
    this.formInit();
  }

  btnEventInit() {
    const self = this;
    //懒得委托了
    // /点击弹出新增数量的弹框
    $("#enterStorageDetail").on("click", "#number", function() {
      if (!self.rowObj) {
        tip.alert("请先选要操作的行", "提示", "warn", 500);
        return;
      }
      $(".insert-returnNumber")
        .removeClass("fide-out hide")
        .addClass("fade-in show");
    });
    // /点击关闭新增数量的弹框
    $("#confirmToReturnNum").on("click", function() {
      const realNum = parseInt($("#return-number").val());
      const { product } = self.rowObj;
      console.log(self.rowObj);
      console.log(product);
      const { cost } = product;
      // if (isNaN(realNum)) return;
      if (cost <= realNum - 1) {
        tip.alert("退货数量不能高于实际数量", "提示", "warn", 500);
        return;
      }
      if (realNum == 0) {
        tip.alert("选择数量不能低于0", "提示", "warn", 500);
        return;
      }
      if (!realNum) {
        tip.alert("选择数量不能为空", "提示", "warn", 500);
        return;
      }
      const { employeeNo, state, type } = self.mainRowObj;
      const { position, uniqueNo, entryStorageNo } = self.rowObj;
      const { productNo } = product;
      const date = new Date();

      const stateLabel = {
        未通过: -1,
        未审核: 0,
        未执行: 1,
        已执行: 2
      };

      const typeLabel = { 采购进仓: 0, 销售退货进仓: 1 };

      const body = {
        date,
        employeeNo,
        signNo: entryStorageNo,
        state: stateLabel[state],
        type: typeLabel[type],
        returnDetails: [
          {
            number: realNum,
            position,
            uniqueNo,
            product: {
              productNo
            }
          }
        ]
      };

      const callback = () => {
        $(".insert-returnNumber")
          .removeClass("fide-out show")
          .addClass("fade-in hide");

        tip.alert("添加成功", "提示", "success", 1000);
        self.tableInit();
      };

      self.addReturn(JSON.stringify(body), callback);
    });
    // 生成退货单
    // $("#enterStorageDetail").on("click", "#confirm", function(e) {
    //   // 数组
    //   const numer = [];
    //   numer.push(parseInt($("#enterStorageDetail #return-number").val(), 10)); //退货数量
    //   const date = new Date();
    //   const employeeNo = $("#enterStorageDetail #enter-employeeNo").val();
    //   const position = $("#enterStorageDetail #enter-position").val();
    //   const product = {};
    //   const uniqueNo = $("#enterStorageDetail #enter-uniqueNo").val();
    //   const returnNo = $("");
    //   const signNo = $("#enterStorageDetail #entryStorage-no").val();
    //   const state = 0;
    //   const type = 0;
    //   const obj = {
    //     number: 10,
    //     position: position,
    //     product: {
    //       productNo: 101
    //     },
    //     uniqueNo: uniqueNo
    //   };
    //   const obj2 = {
    //     number: 10,
    //     position: position,
    //     product: {
    //       productNo: 101
    //     },
    //     uniqueNo: uniqueNo
    //   };
    //   let body1 = {
    //     employeeNo: employeeNo,
    //     returnDetails: [obj],
    //     returnDetails: [obj2],
    //     returnNo: 0,
    //     signNo: signNo,
    //     state: state,
    //     type: 1
    //   }; //参数
    //   //
    //   let body = JSON.stringify(body1);
    //   $.ajax({
    //     url: `${self.baseUrl}returnMaster`,
    //     method: "post",
    //     data: body,
    //     contentType: "application/json; charset=UTF-8"
    //   }).then(res => {
    //     //TODO:这里放请求成功后的事件，比如关闭弹窗
    //     alert("cheng");
    //   });
    // });
  }

  //添加退单
  addReturn(body, callback) {
    $.ajax({
      url: `${this.baseUrl}returnMaster`,
      method: "post",
      data: body,
      contentType: "application/json; charset=UTF-8"
    }).then(res => {
      callback && callback();
    });
  }

  getTableBody(res) {
    if (!res) {
      $(this.element).html();
      return;
    }
    const value = res.value;

    // const body = value.map(({ number, product }) => {
    //   return { ...product, number };
    // });
    return value;
  }
  //进仓弹窗-表头
  tableHead = {
    productNo: "商品编号",
    brand: "商品品牌",
    type: "商品类型",
    gWeight: "商品克重",
    standard: "商品标准",
    level: "商品类型",
    unit: "商品单位",
    cost: "商品件数",
    price: "商品价格",
    number: "进仓数量"
  };
}

// 退货明细表单
class ReturnWarehouseDetail extends Table {
  constructor({ url, noParam, mainRowObj }) {
    super({
      url,
      noParam,
      rootElement: "#retrunHouseDetail",
      element: "#returnHouseProductTable"
    });
    this.element = "#returnHouseProductTable";
    this.url = url;
    this.mainRowObj = mainRowObj;
    this.init();
  }
  formInit() {
    const { returnNo, signNo, type, state, employeeNo, date } = this.mainRowObj;
    // type = { 0: "采购进仓", 1: "销售退货进仓" };
    $("#retrunHouseDetail #return-No").val(returnNo);
    $("#retrunHouseDetail #signNo").val(signNo);
    $("#retrunHouseDetail #return-state").val(state);
    $("#retrunHouseDetail #return-employeeNo").val(employeeNo);
    $("#retrunHouseDetail #return-date").val(date);
    $("#retrunHouseDetail #return-type").val(type);
  }

  init() {
    super.tableInit();
    this.btnEventInit();
    this.formInit();
  }

  btnEventInit() {
    const self = this;
    //懒得委托了
    // /点击弹出新增数量的弹框
    $("#retrunHouseDetail").on("click", "#number", function() {
      if (!self.rowObj) {
        tip.alert("请先选要操作的行", "提示", "warn", 500);
        return;
      }
      $(".insert-returnNumber")
        .removeClass("fide-out hide")
        .addClass("fade-in show");
    });

    // /点击弹出退货数量的弹框
    $("#retrunHouseDetail").on("click", "#returncss", function() {
      if (!self.rowObj) {
        tip.alert("请先选要操作的行", "提示", "warn", 500);
        return;
      }
      $(".insert-returnNumber")
        .removeClass("fide-out hide")
        .addClass("fade-in show");
    });

    // /点击关闭新增数量的弹框
    $("#confirmToReturnNum").on("click", function() {
      const realNum = parseInt($("#return-number").val());
      console.log(realNum);
      const { cost } = self.rowObj;
      // console.log("退出");
      console.log(cost);
      if (cost <= realNum - 1) {
        tip.alert("退货数量不能高于实际数量", "提示", "warn", 500);
        return;
      }
      if (realNum == 0) {
        tip.alert("选择数量不能低于0", "提示", "warn", 500);
        return;
      }
      if (!realNum) {
        tip.alert("选择数量不能为空", "提示", "warn", 500);
        return;
      }
      console.log(self.mainRowObj);
      console.log(self.rowObj);
      const { returnNo } = self.mainRowObj;
      const { productNo } = self.rowObj;

      const body = {
        number: realNum,
        product: {
          productNo
        },
        returnNo
      };

      console.log(body);

      const callback = () => {
        $(".insert-returnNumber")
          .removeClass("fide-out show")
          .addClass("fade-in hide");

        tip.alert("修改成功", "提示", "success", 1000);
        self.tableInit();
      };

      self.alterReturn(JSON.stringify(body), callback);
    });
  }

  // 生成退货明细单
  alterReturn(body, callback) {
    $.ajax({
      url: `${this.baseUrl}returnDetail`,
      method: "put",
      data: body,
      contentType: "application/json; charset=UTF-8"
    }).then(res => {
      callback && callback();
    });
  }

  getTableBody(res) {
    if (!res) {
      $(this.element).html();
      return;
    }
    const value = res.value;

    const body = value.map(({ number, product, position, uniqueNo }) => {
      $("#retrunHouseDetail #return-position").val(position);
      $("#retrunHouseDetail #return-uniqueNo").val(uniqueNo);

      return { ...product, number };
    });

    return body;
  }

  //退仓弹窗-表头
  tableHead = {
    productNo: "商品编号",
    brand: "商品品牌",
    type: "商品类型",
    gWeight: "商品克重",
    standard: "商品标准",
    level: "商品类型",
    unit: "商品单位",
    cost: "商品数量",
    price: "商品价格",
    number: "退货数量"
  };
}

function getEnterWarehousDetail(id, mainRowObj) {
  const url = (baseUrl, pageNum) => {
    return `${baseUrl}/enterStorageDetail/${pageNum}/10/${id}`;
  };
  new EnterWarehouseDetail({ url, noParam: true, mainRowObj });
}

// 获得采购退货单详细情况
function getBuyReturnDetail(id, mainRowObj) {
  const url = (baseUrl, pageNum) => {
    return `${baseUrl}/returnDetail/${pageNum}/10/${id}`;
  };
  new ReturnWarehouseDetail({ url, noParam: true, mainRowObj });
}

function timeTransform(val) {
  const date = new Date(val);
  const Y = date.getFullYear() + "-";
  const M =
    (date.getMonth() + 1 < 10
      ? "0" + (date.getMonth() + 1)
      : date.getMonth() + 1) + "-";
  const D = (date.getDate() < 10 ? "0" + date.getDate() : date.getDate()) + " ";
  const h =
    (date.getHours() < 10 ? "0" + date.getHours() : date.getHours()) + ":";
  const m =
    (date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes()) +
    ":";
  const s =
    date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();

  return Y + M + D + h + m + s;
}
